<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="合同编号" prop="templateId">
        <el-input
          v-model="queryParams.templateId"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同名称" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入合同名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="usageStatus">
        <el-select
          v-model="queryParams.usageStatus"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="dict in statusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['contract:template:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['contract:template:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['contract:template:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['order:rule:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-row :gutter="10" class="mb8">
      <el-radio-group
        v-model="queryParams.usageStatus"
        @change="handleQuery"
      >
        <el-radio-button :label="undefined"
          >全部（{{ statistics.templateNumber }}）</el-radio-button
        >
        <!-- <el-radio-button label="1">待编辑（123）</el-radio-button> -->
        <el-radio-button label="1"
          >启用（{{ statistics.enableTemplateNumber }}）</el-radio-button
        >
        <el-radio-button label="0"
          >禁用（{{ statistics.disabledTemplateNumber }}）</el-radio-button
        >
      </el-radio-group>
    </el-row>
    <div class="info">
      <i class="el-icon-info"></i> <span>已选择</span> {{ ids.length }}
      <span>项</span> <label @click="clearSelect" class="clear">清空</label>
    </div>
    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      ref="table"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板编号" align="center" prop="templateId" />
      <el-table-column label="模板名称" align="center" prop="templateName" />
      <el-table-column label="申请人信息" align="center" prop="createName">
        <template slot-scope="scope">
          <span>
            {{ scope.row.createName }} - {{ scope.row.createMobile }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="适应租期" align="center" prop="apartmentType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.dict_unsubscribe_rule_type"
            :value="scope.row.apartmentType"
          />
        </template>
      </el-table-column>
      <el-table-column label="启用" align="center" prop="usageStatus">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.usageStatus"
            active-value="1"
            inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['contract:template:detail']"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['contract:template:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['contract:template:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 新增/编辑 -->
    <Add v-model="open" :title="title" :formData="form" @success="handleQuery" />
    <!-- 详情 -->
    <Detail v-model="detailVisible" :title="title" :formData="form" />
  </div>
</template>

<script>
import {
  getUnsubscribeRule,
} from "@/api/house/rule";

import {
  listContractTemplate,
  getContractTemplateStatistics,
  delContractTemplate,
  changeUsageStatus,
  getContractTemplate,
} from "@/api/contract/template";
import Add from './components/Add.vue'
import Detail from './components/Detail.vue'

export default {
  name: "Template",
  dicts: [
    "dict_unsubscribe_rule_type",
    "dict_cancel_type",
    "dict_enable_status",
  ],
  components:{
    Add,
    Detail
  },
  data() {
    var validateCancelType = (rule, value, callback) => {
      if (value === "1") {
        callback();
      } else {
        if (
          !this.form.freeDays ||
          !this.form.minDays ||
          !this.form.maxDays ||
          !this.form.rent ||
          !this.form.cashPledge ||
          !this.form.todayRent ||
          !this.form.todayCashPledge
        ) {
          callback(new Error("数据不能为空"));
        }
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      //模板详情数据
      unsubscribeRuleData: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //详情弹窗
      detailVisible: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateId: undefined,
        templateName: undefined,
        usageStatus: undefined,
      },
      //统计数据
      statistics:{},
      //状态列表
      statusList: [
        { label: "启用", value: "1" },
        { label: "禁用", value: "0" },
      ],
      // 表单参数
      form: {},
    };
  },
  created() {
    this.init();
  },
  methods: {
    init(){
      getContractTemplateStatistics().then(res=>{
        this.statistics = res.data
      })
      this.getList()
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      listContractTemplate(this.addDateRange(this.queryParams, this.dateRange))
        .then((response) => {
          this.list = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        templateName: "", //合同模板名称
        content: "", //合同模板内容
        apartmentType: undefined, //公寓类型(出租周期)：1短租公寓;2长租公寓
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.templateId);
      this.single = selection.length != 1;
      console.log("single", this.single);
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const templateId = row.templateId || this.ids;
      getContractTemplate(templateId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改模板";
      });
    },
    handleDetail(row) {
      this.reset();
      const templateId = row.templateId || this.ids;
      getContractTemplate(templateId).then((response) => {
        this.form = response.data;
        this.detailVisible = true;
        this.title = "详情";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const templateIds = row.templateId || this.ids;
      this.$modal
        .confirm('是否确认删除合同模板编号为"' + templateIds + '"的数据项？')
        .then(function () {
          return delContractTemplate(templateIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/post/export",
        {
          ...this.queryParams,
        },
        `post_${new Date().getTime()}.xlsx`
      );
    },
    // 模板状态修改
    handleStatusChange(row) {
      console.log("usageStatus", row.usageStatus);
      let text = row.usageStatus === "1" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '""' + row.templateName + '"合同模板吗？')
        .then(function () {
          return changeUsageStatus(row.templateId, row.usageStatus);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          console.log("err");
          row.usageStatus = row.usageStatus === "1" ? "0" : "1";
        });
    },
    //请空选择项
    clearSelect() {
      this.$refs.table.clearSelection();
    },
  },
};
</script>
<style lang="scss" scoped>
.info {
  padding: 10px 15px;
  margin: 15px 0;
  background: #e6f7ff;
  color: #1890ff;
  span {
    color: #565c5f;
  }
  .clear {
    margin-left: 20px;
    cursor: pointer;
  }
}
.detail-item {
  margin-bottom: 20px;
  .label {
    color: #7f7f7f;
    margin-bottom: 10px;
  }
  .value {
    font-size: 16px;
  }
}
</style>
